package com.neudu.yiyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.pojo.Customer;
import com.neudu.yiyang.pojo.Customerpreference;
import com.neudu.yiyang.pojo.Food;
import com.neudu.yiyang.pojo.Meal;
import com.neudu.yiyang.service.CustomerService;
import com.neudu.yiyang.service.CustomerpreferenceService;
import com.neudu.yiyang.service.FoodService;
import com.neudu.yiyang.service.MealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RestController
public class MealController {
    @Autowired
    JSONReturn jsonReturn;

    @Autowired
    MealService mealService;

    @Autowired
    FoodService foodService;

    @Autowired
    CustomerService customerService;

    @Autowired
    CustomerpreferenceService customerpreferenceService;

    @RequestMapping("get_meals")
    public String getMeals(@RequestBody Map<String, String> request) {
        String keyword = request.get("keyword");
        try {
            Object meals = mealService.getMealsWithFoodDetails(keyword);
            System.out.println("后端返回的 meals 数据: " + meals);
            return jsonReturn.returnSuccess(meals);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("add_food")
    public String addFood(@RequestBody Food food) {
        try {
            foodService.save(food);
            return jsonReturn.returnSuccess(Map.of("foodId", food.getId()));
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("add_meal")
    public String addMeal(@RequestBody Map<String, Object> request) {
        try {
            // 提取食物信息
            String foodName = (String) request.get("foodName");
            String foodPriceStr = (String) request.get("foodPrice");
            BigDecimal foodPrice = null;
            if (foodPriceStr != null && !foodPriceStr.isEmpty()) {
                try {
                    foodPrice = new BigDecimal(foodPriceStr);
                } catch (NumberFormatException e) {
                    return jsonReturn.returnError("食物价格必须是有效的数字格式");
                }
            }

            // 保存食物信息
            Food food = new Food();
            food.setFoodName(foodName);
            food.setPrice(foodPrice);
            foodService.save(food);

            // 提取膳食信息
            Meal meal = new Meal();
            meal.setWeekDay((String) request.get("weekDay"));

            Object mealTypeObj = request.get("mealType");
            Integer mealType = null;
            if (mealTypeObj != null) {
                if (mealTypeObj instanceof String) {
                    try {
                        mealType = Integer.parseInt((String) mealTypeObj);
                    } catch (NumberFormatException e) {
                        return jsonReturn.returnError("餐食类型必须是有效的整数格式");
                    }
                } else if (mealTypeObj instanceof Integer) {
                    mealType = (Integer) mealTypeObj;
                } else {
                    return jsonReturn.returnError("餐食类型数据类型错误");
                }
            }
            meal.setMealType(mealType);

            meal.setTaste((String) request.get("taste"));

            Object isDeletedObj = request.get("isDeleted");
            Integer isDeleted = null;
            if (isDeletedObj != null) {
                if (isDeletedObj instanceof String) {
                    try {
                        isDeleted = Integer.parseInt((String) isDeletedObj);
                    } catch (NumberFormatException e) {
                        return jsonReturn.returnError("是否删除字段必须是有效的整数格式");
                    }
                } else if (isDeletedObj instanceof Integer) {
                    isDeleted = (Integer) isDeletedObj;
                } else {
                    return jsonReturn.returnError("是否删除字段数据类型错误");
                }
            }
            meal.setIsDeleted(isDeleted);

            meal.setFoodId(food.getId());

            // 保存膳食信息
            mealService.save(meal);

            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("edit_mealby")
    public String editMealBy(@RequestBody Meal meal){
        try {
            mealService.updateById(meal);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("delete_mealby")
    public String deleteMealBy(@RequestBody Map<String, Integer> request){
        try {
            Integer id = request.get("id");
            if (id == null) {
                return jsonReturn.returnError("id 参数缺失");
            }
            Meal meal = mealService.getById(id);
            if (meal != null) {
                Integer foodId = meal.getFoodId();
                if (foodId != null) {
                    foodService.removeById(foodId);
                }
            }
            mealService.removeById(id);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }


    /**
     * 获取客户偏好列表（包含嵌套的 Customer 对象）
     */
    @PostMapping("/get_CustomerPreference_List")
    public String getCustomerPreferenceList(@RequestBody Map<String, String> request) {
        try {
            String keyword = request.get("keyword");
            QueryWrapper<Customerpreference> preferenceWrapper = new QueryWrapper<>();
            if (keyword != null && !"".equals(keyword)) {
                // 根据关键字模糊匹配 customer_name
                List<Customer> customers = customerService.list(new QueryWrapper<Customer>().like("customer_name", keyword));
                if (customers.isEmpty()) {
                    return jsonReturn.returnSuccess(); // 没有匹配的客户直接返回空列表
                }
                // 提取匹配客户的 ID 列表
                List<Integer> customerIds = customers.stream().map(Customer::getId).toList();
                preferenceWrapper.in("customer_id", customerIds);
            }

            // 查询 customerpreference 表数据
            List<Customerpreference> preferenceList = customerpreferenceService.list(preferenceWrapper);

            // 为每个 CustomerPreference 填充对应的 Customer 对象
            for (Customerpreference preference : preferenceList) {
                Customer customer = customerService.getById(preference.getCustomerId());
                preference.setCustomer(customer);
            }

            return jsonReturn.returnSuccess(preferenceList);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 新增添加客户偏好的方法
    @PostMapping("/addCustomerPreference")
    public String addCustomerPreference(@RequestBody Customerpreference customerpreference) {
        try {
            boolean result = customerpreferenceService.save(customerpreference);
            if (result) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("添加客户偏好失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /**
     * 编辑客户信息
     */
    @PostMapping("/editCustomer")
    public String editCustomer(@RequestBody Map<String, Object> request) {
        try {
            // 仅获取客户ID和偏好信息
            Integer id = (Integer) request.get("customer_id");
            String preferences = (String) request.get("preferences");
            String attention = (String) request.get("attention");
            String remark = (String) request.get("remark");

            // 校验客户ID是否有效
            if (id == null || id <= 0) {
                return jsonReturn.returnError("无效的客户ID");
            }

            // 查询客户偏好信息是否存在
            QueryWrapper<Customerpreference> preferenceWrapper = new QueryWrapper<>();
            preferenceWrapper.eq("customer_id", id);
            Customerpreference preference = customerpreferenceService.getOne(preferenceWrapper);

            if (preference == null) {
                // 若不存在，可选择创建新记录或返回错误（根据业务需求决定）
                return jsonReturn.returnError("客户偏好信息不存在");
            }

            // 更新偏好信息
            preference.setPreferences(preferences);
            preference.setAttention(attention);
            preference.setRemark(remark);
            boolean updateResult = customerpreferenceService.updateById(preference);

            if (updateResult) {
                return jsonReturn.returnSuccess("偏好信息更新成功");
            } else {
                return jsonReturn.returnError("偏好信息更新失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("操作失败：" + e.getMessage());
        }
    }

    /**
     * 删除客户偏好信息（只删除 customerpreference 表中的数据）
     */
    @PostMapping("/deleteCustomer")
    public String deleteCustomer(@RequestBody Map<String, Integer> request) {
        try {
            // 获取前端传递的 customer_id
            Integer customerId = request.get("customer_id");
            if (customerId == null || customerId <= 0) {
                return jsonReturn.returnError("无效的 customer_id 参数");
            }

            // 删除 customerpreference 表中关联的记录
            QueryWrapper<Customerpreference> preferenceWrapper = new QueryWrapper<>();
            preferenceWrapper.eq("customer_id", customerId);

            boolean preferenceDeleteResult = customerpreferenceService.remove(preferenceWrapper);
            if (preferenceDeleteResult) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("删除客户信息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
}
